package cn.kn.common.config.shiro;


import cn.kn.common.config.jwt.JWTToken;
import cn.kn.common.exception.CustomException;
import cn.kn.common.model.RCode;
import cn.kn.common.utils.JWTUtils;
import cn.kn.sys.dao.RecouresDao;
import cn.kn.sys.mapper.UserMapper;
import cn.kn.sys.model.User;
import cn.kn.sys.model.UserExample;
import cn.kn.sys.vo.ActiveUser;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserRealm extends AuthorizingRealm {


    private final UserMapper userMapper;
    private final RecouresDao recouresDao;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        List<String> permissions = new ArrayList<>(activeUser.getPermissions());

        //授权权限
        if (!CollectionUtils.isEmpty(permissions)) {
            authorizationInfo.addStringPermissions(permissions);
        }
        return authorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtils.getUsername(token);

        if (StringUtils.isEmpty(username)) {
            throw new CustomException(RCode.TOKEN_ERROR);
        }

        if(JWTUtils.isExpire(token)){
            throw new CustomException(RCode.TOKEN_INVALID);
        }

        UserExample example=new UserExample();
        example.createCriteria().andNameEqualTo(username).andIsdelEqualTo(false);
        List<User> users=userMapper.selectByExample(example);

        if(CollectionUtils.isEmpty(users)){
            throw new CustomException(RCode.USER_NOT_EXIST);
        }

        User user=users.get(0);
        if (! JWTUtils.verify(token, username, user.getPassword())) {
            throw new CustomException(RCode.USER_NOT_EXIST);
        }

        List<String> perms=recouresDao.getPermsByUserId(user.getId())
                .stream().filter(p->!StringUtils.isEmpty(p))
                .flatMap(p->Arrays.stream(p.split(",")))
                .collect(Collectors.toList());

        //过滤出url,和用户的权限
        ActiveUser activeUser = new ActiveUser();
        activeUser.setUser(user);
        activeUser.setPermissions(perms);
        return new SimpleAuthenticationInfo(activeUser, token, getName());
    }
}
